import { useState, useEffect, useRef } from 'react'
import AuthProvider from './contexts/AuthContext'
import useAuth from './contexts/useAuth'
import AuthPage from './pages/AuthPage'
import './App.css'
import apiService from './api/apiService'

// 职场沟通助手界面组件
function WorkplaceAssistant() {
  const [messages, setMessages] = useState([
    {
      id: Date.now() - 1000,
      role: 'assistant',
      content: '您好！我是您的职场沟通助手。我可以帮您：\n1. 撰写专业邮件\n2. 准备会议纪要\n3. 提供演讲技巧\n4. 解决职场沟通问题\n5. 分析沟通场景\n\n请告诉我您需要哪方面的帮助？',
      avatar: '💼'
    }
  ])
  const [inputValue, setInputValue] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [connectionStatus, setConnectionStatus] = useState('connected')
  const [activeCategory, setActiveCategory] = useState('all')
  const quickResponses = [
    '帮我写一封会议邀请邮件',
    '如何有效进行跨部门沟通？',
    '准备一个简短的项目进展报告',
    '如何处理工作中的冲突？'
  ]

  const messagesEndRef = useRef(null)
  const { user, logout } = useAuth()

  // 自动滚动到最新消息
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  // 初始化WebSocket连接和订阅
  useEffect(() => {
    // 订阅实时消息
    const unsubscribeMessages = apiService.chat?.subscribeToMessages ? apiService.chat.subscribeToMessages((message) => {
      // 将API消息格式转换为我们的界面格式
      const formattedMessage = {
        id: message.id || Date.now(),
        role: message.sender === 'user' ? 'user' : 'assistant',
        content: message.content,
        avatar: message.sender === 'user' ? '👤' : '💼',
        category: message.category || 'all'
      }
      setMessages(prevMessages => [...prevMessages, formattedMessage])
    }) : () => {};

    // 订阅连接状态
    const unsubscribeConnection = apiService.connection?.subscribeToConnectionStatus ? apiService.connection.subscribeToConnectionStatus((status) => {
      setConnectionStatus(status.state)
    }) : () => {};

    // 组件卸载时取消订阅
    return () => {
      unsubscribeMessages()
      unsubscribeConnection()
    }
  }, [])

  // 发送消息
  const handleSendMessage = async (text = null) => {
    const messageText = text || inputValue.trim()
    if (!messageText) return

    const newUserMessage = {
      id: Date.now(),
      role: 'user',
      content: messageText,
      avatar: '👤',
      timestamp: new Date().toLocaleTimeString()
    }

    setMessages(prev => [...prev, newUserMessage])
    setInputValue('')
    setIsLoading(true)

    try {
      // 确保messageText是字符串类型
      const messageStr = String(messageText || '');
      
      // 根据消息内容判断分类
      let category = 'all'
      if (messageStr.includes('邮件') || messageStr.includes('email')) category = 'email'
      if (messageStr.includes('会议') || messageStr.includes('meeting')) category = 'meeting'
      if (messageStr.includes('报告') || messageStr.includes('report')) category = 'report'
      if (messageStr.includes('冲突') || messageStr.includes('conflict')) category = 'conflict'

      // 模拟API响应，实际项目中应调用apiService
      // const response = await apiService.chat.sendMessage(messageText)
      
      // 模拟延迟
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 模拟响应内容
      let responseContent = ''
      if (messageStr.includes('邮件') || messageStr.includes('email')) {
        responseContent = '以下是一封专业的会议邀请邮件模板：\n\n主题：【会议邀请】项目进度讨论会议\n\n尊敬的团队成员：\n\n诚挚邀请您参加即将举行的项目进度讨论会议。\n\n时间：[具体日期和时间]\n地点：[会议地点/线上会议链接]\n议程：\n1. 项目当前进度回顾\n2. 下一阶段工作计划\n3. 遇到的问题与解决方案\n\n请各位准时参加，并提前准备相关材料。如有任何疑问，请随时联系我。\n\n祝工作顺利！\n\n[您的姓名]\n[您的职位]'
      } else if (messageStr.includes('会议') || messageStr.includes('meeting')) {
        responseContent = '有效的会议沟通技巧：\n\n1. 会前准备：\n   - 明确会议目标和议程\n   - 提前发送会议资料给参与者\n   - 准备简洁明了的演示材料\n\n2. 会中技巧：\n   - 准时开始和结束\n   - 鼓励所有参与者发言\n   - 保持讨论聚焦在议题上\n   - 记录关键决策和行动项\n\n3. 会后跟进：\n   - 及时发送会议纪要\n   - 跟进行动项的完成情况\n   - 收集反馈以改进未来会议'
      } else if (messageStr.includes('报告') || messageStr.includes('report')) {
        responseContent = '项目进展报告模板：\n\n# 项目进展报告\n\n## 1. 项目概况\n- 项目名称：[项目名称]\n- 报告周期：[起始日期] 至 [结束日期]\n- 当前阶段：[阶段描述]\n- 总体进度：[百分比]\n\n## 2. 已完成工作\n- [任务1]：[完成情况描述]\n- [任务2]：[完成情况描述]\n\n## 3. 进行中工作\n- [任务1]：[进度描述]，预计[完成日期]完成\n- [任务2]：[进度描述]，预计[完成日期]完成\n\n## 4. 遇到的问题与风险\n- [问题1]：[描述]，[解决方案]\n\n## 5. 下一阶段计划\n- [计划1]：[描述]，计划于[日期]开始\n\n## 6. 资源需求\n- [资源需求描述]'
      } else if (messageStr.includes('冲突') || messageStr.includes('conflict')) {
        responseContent = '处理工作冲突的有效策略：\n\n1. 保持冷静，避免情绪化反应\n2. 积极倾听对方的观点和感受\n3. 用"我"语句表达自己的感受，避免指责\n4. 寻找共同点，强调共同目标\n5. 提出多种解决方案，共同评估\n6. 聚焦问题本身，不针对个人\n7. 如果无法立即解决，约定后续讨论时间\n\n记住，建设性的冲突可以促进团队成长和创新，关键在于如何管理和解决冲突。'
      } else {
        responseContent = '感谢您的咨询！我理解您在' + messageStr.substring(0, 20) + '...方面的需求。\n\n作为您的职场沟通助手，我可以提供以下支持：\n\n1. 专业文档撰写（邮件、报告、提案等）\n2. 会议管理和沟通技巧\n3. 职场关系和冲突处理\n4. 演讲和演示准备\n5. 跨文化和跨部门沟通建议\n\n请告诉我您具体需要哪方面的帮助，我将为您提供更有针对性的支持。'
      }
      
      // 将AI回复添加到消息列表
      const aiMessage = {
        id: Date.now() + 1,
        role: 'assistant',
        content: responseContent,
        avatar: '💼',
        category: category,
        timestamp: new Date().toLocaleTimeString()
      }
      setMessages(prev => [...prev, aiMessage])
      
    } catch (error) {
      console.error('发送消息失败:', error)
      // 添加错误消息
      const errorMessage = {
        id: Date.now() + 2,
        role: 'assistant',
        content: '抱歉，我暂时无法处理您的请求。请稍后再试。',
        avatar: '💼',
        timestamp: new Date().toLocaleTimeString()
      }
      setMessages(prev => [...prev, errorMessage])
    } finally {
      setIsLoading(false)
    }
  }

  // 使用快捷回复
  const handleQuickResponse = (text) => {
    handleSendMessage(text)
  }



  // 处理回车键发送
  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSendMessage()
    }
  }

  // 过滤消息
  const filteredMessages = activeCategory === 'all' 
    ? messages 
    : messages.filter(msg => msg.category === activeCategory || msg.role === 'user')

  return (
    <div className="workplace-container">
      <div className="workplace-header">
        <div className="logo-container">
          <span className="logo-icon">💼</span>
          <h1>职场沟通助手</h1>
        </div>
        <div className="user-info">
          
          <span className="user-name">{user?.username || '用户'}</span>
          <button onClick={logout} className="logout-button">退出</button>
        </div>
      </div>

      {/* 功能分类标签 */}
      <div className="category-tabs">
        <button 
          className={`category-tab ${activeCategory === 'all' ? 'active' : ''}`}
          onClick={() => setActiveCategory('all')}
        >
          全部
        </button>
        <button 
          className={`category-tab ${activeCategory === 'email' ? 'active' : ''}`}
          onClick={() => setActiveCategory('email')}
        >
          邮件模板
        </button>
        <button 
          className={`category-tab ${activeCategory === 'meeting' ? 'active' : ''}`}
          onClick={() => setActiveCategory('meeting')}
        >
          会议管理
        </button>
        <button 
          className={`category-tab ${activeCategory === 'report' ? 'active' : ''}`}
          onClick={() => setActiveCategory('report')}
        >
          报告撰写
        </button>
        <button 
          className={`category-tab ${activeCategory === 'conflict' ? 'active' : ''}`}
          onClick={() => setActiveCategory('conflict')}
        >
          冲突处理
        </button>
      </div>
      
      <div className="workplace-content">
        <div className="chat-messages">
          {filteredMessages.length === 0 ? (
            <div className="no-messages">暂无相关消息</div>
          ) : (
            filteredMessages.map(message => (
              <div 
                key={message.id} 
                className={`message ${message.role === 'user' ? 'user-message' : 'assistant-message'}`}
              >
                <div className="message-header">
                  <div className="avatar">{message.avatar}</div>
                  <span className="sender-name">
                    {message.role === 'user' ? '我' : '助手'}
                  </span>
                  {message.timestamp && (
                    <span className="message-time">{message.timestamp}</span>
                  )}
                </div>
                <div className="message-content">
                  {String(message.content || '').split('\n').map((line, index) => (
                    <p key={index}>{line}</p>
                  ))}
                </div>
              </div>
            ))
          )}
          {isLoading && (
            <div className="message assistant-message">
              <div className="message-header">
                <div className="avatar">💼</div>
                <span className="sender-name">助手</span>
              </div>
              <div className="message-content">
                <div className="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>
        
        {/* 快捷回复区域 */}
        <div className="quick-responses">
          <p className="quick-response-title">快速开始：</p>
          <div className="quick-response-buttons">
            {quickResponses.map((response, index) => (
              <button 
                key={index} 
                className="quick-response-btn"
                onClick={() => handleQuickResponse(response)}
              >
                {response}
              </button>
            ))}
          </div>
        </div>
      </div>
      
      <div className="chat-input-container">
        <div className="input-wrapper">
          <textarea
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="请描述您在工作中遇到的沟通问题，或需要的文档模板..."
            rows={1}
            className="chat-input"
          />
          <button 
            onClick={handleSendMessage} 
            disabled={isLoading || !inputValue.trim()}
            className="send-button"
          >
            {isLoading ? '处理中...' : '发送'}
          </button>
        </div>
        <div className="input-actions">
          <span className="action-hint">按Enter发送，Shift+Enter换行</span>
        </div>
      </div>
    </div>
  )
}

// 主应用组件
function AppContent() {
  const { user, loading } = useAuth()

  if (loading) {
    return (
      <div className="loading-container">
        <div className="loading-spinner"></div>
        <p>正在初始化职场沟通助手...</p>
      </div>
    )
  }

  return user ? <WorkplaceAssistant /> : <AuthPage />;
}

// 根组件，使用AuthProvider包装
function App() {
  return (
    <AuthProvider>
      <AppContent />
    </AuthProvider>
  )
}

export default App
